package com.atguigu.flink.chapter05.source;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Flink04_Source_custom {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStreamSource<WaterSensor> stream = env.addSource(new SocketSource("hadoop162", 9999));

        stream.print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class SocketSource implements SourceFunction<WaterSensor> {

        private String host;
        private int port;
        private boolean cancel = false;

        public SocketSource(String host, int port) {
            this.host = host;
            this.port = port;
        }

        // 循环不断从数据源读取数据
        @Override
        public void run(SourceContext<WaterSensor> ctx) throws Exception {
            // socket 编程
            Socket socket = new Socket(host, port);
            InputStream is = socket.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

            String line = reader.readLine();
            while(!cancel && line != null) {
                String[] data = line.split(",");
                ctx.collect(new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2])));
                line = reader.readLine();
            }

        }

        @Override
        public void cancel() {
            this.cancel = true;
        }
    }
}
